import api from './api'

export interface IpWhitelistEntry {
  ip: string
  description: string
  added_at: string
}

export interface IpCheckResult {
  allowed: boolean
  client_ip: string
}

export const ipWhitelistApi = {
  // 检查当前IP是否在白名单中
  async checkAccess(): Promise<IpCheckResult> {
    try {
      return await api.get('/settings/ip-whitelist/check')
    } catch (error) {
      console.error('检查IP白名单失败:', error)
      return { allowed: false, client_ip: 'unknown' }
    }
  },

  // 获取IP白名单列表
  async getWhitelist(): Promise<{ success: boolean; data: IpWhitelistEntry[]; current_ip: string }> {
    return api.get('/settings/ip-whitelist')
  },

  // 添加IP到白名单
  async addIp(ip: string, description: string = ''): Promise<{ success: boolean; message: string }> {
    return api.post('/settings/ip-whitelist/add', { ip, description })
  },

  // 从白名单移除IP
  async removeIp(ip: string): Promise<{ success: boolean; message: string }> {
    return api.delete(`/settings/ip-whitelist/${encodeURIComponent(ip)}`)
  }
}

// IP白名单检查Hook
let ipCheckCache: { result: IpCheckResult | null; timestamp: number } = {
  result: null,
  timestamp: 0
}

const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

export async function checkIpWhitelist(): Promise<boolean> {
  const now = Date.now()
  
  // 检查缓存是否有效
  if (ipCheckCache.result && (now - ipCheckCache.timestamp) < CACHE_DURATION) {
    return ipCheckCache.result.allowed
  }
  
  // 重新检查
  try {
    const result = await ipWhitelistApi.checkAccess()
    ipCheckCache = {
      result,
      timestamp: now
    }
    return result.allowed
  } catch (error) {
    console.error('IP白名单检查失败:', error)
    return false
  }
}

// 清除缓存
export function clearIpCheckCache() {
  ipCheckCache = { result: null, timestamp: 0 }
}
